package com.chuhe.lottery.controller;

import com.chuhe.lottery.config.ThreadPoolConfig;
import com.chuhe.lottery.service.LotteryService;
import com.chuhe.lottery.service.adapter.ResultAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 楚河
 * @Date: 2025年06月03日16:22
 */
@RestController
@RequestMapping("/test")
@Slf4j
public class LotteryController {
    @Autowired
    private ThreadPoolConfig threadPoolConfig;
    @Autowired
    private LotteryService lotteryService;
    @Autowired
    private ResultAdapter resultAdapter;

    @PostMapping("/lottery")
    public HashMap<String,Object> lottery(){
        HashMap<String, Object> result = new HashMap<>();
        long startTime = System.currentTimeMillis();//启动时间
        CountDownLatch latch = new CountDownLatch(1000);

        // 使用自定义的线程池模拟千人并发
        ThreadPoolTaskExecutor lotteryExecutor = threadPoolConfig.LotteryExecutor();
        for (int i = 0; i < 1000; i++) {
            final int userId = i + 1;
            lotteryExecutor.execute(() -> {
                try {
                    HashMap<String, Object> lotteryResult = lotteryService.lottery(userId);
                    if(Objects.isNull(lotteryResult.get("result"))){
                        log.warn("用户{}抽奖结果为空，奖池已空", userId);
                    }
                }catch (Exception e){
                    log.error("用户{}抽奖失败",userId,e);
                }
            });
        }

        try {
            // TODO 等待所有任务完成，最多等待10秒
            boolean completed = latch.await(10, TimeUnit.SECONDS);
            if (!completed) {
                log.warn("部分任务超时未完成");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("等待任务完成被异常中断", e);
        } finally {
            // 关闭线程池
            lotteryExecutor.shutdown();
        }

        long endTime = System.currentTimeMillis();
        // 结果封装 返回
        return resultAdapter.buildResultAdapter(result,endTime - startTime);
    }

}
